/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package buggywar;

import Classes.User;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author paly
 */
public class UserSessionFilter implements Filter {
    private FilterConfig filterConfig;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest hreq = (HttpServletRequest) request;
        HttpServletResponse hres = (HttpServletResponse) response;
        HttpSession session = hreq.getSession();

        User user = (User) session.getAttribute("user");
        if (user != null) {
            chain.doFilter(request, response);
            return;
        }

        if (!(hreq.getRequestURL().toString().contains("index.jsp")
            || hreq.getRequestURL().toString().contains("register_user.jsp"))) {
            RequestDispatcher dispatcher = request.getRequestDispatcher(hreq.getServletPath() + "/index.jsp");
            dispatcher.forward(request, response);
        }

        chain.doFilter(request, response);
    }

    public void destroy() {
        this.filterConfig = null;
    }
}
